<template lang="html">
    <div id="ProductList" v-loading.fullscreen.lock="loading" element-loading-text="拼命加载中">
        <db-breadcrumb></db-breadcrumb>
        <div class="db-content-inner">
            <div class="filters">
                <div class="filter">
                    <el-input placeholder="产品名称" v-model="filters.productName"></el-input>
                </div>
                <div class="filter">
                    <el-select placeholder="产品类型" v-model="filters.productType" clearable>
                        <el-option v-for="item in productTypeList" :value="item.value" :label="item.name"></el-option>
                    </el-select>
                </div>
                <div class="filter">
                    <el-date-picker type="daterange" placeholder="添加日期" style="width:250px" v-model="filters.addDate"></el-date-picker>
                </div>
                <el-button type="primary" @click="handleSearch()">搜索</el-button>
                <el-button type="primary" @click="handleAdd()">创建</el-button>
            </div>
            <el-table :data="tableData" ref="table" style="width: 100%" border stripe>
                <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>
                <el-table-column prop="productTypeName" label="产品类型"></el-table-column>
                <el-table-column prop="productPrice" label="产品单价"></el-table-column>
                <el-table-column prop="productPayCount" label="已售数量" inline-template>
                    <div>{{row.productPayCount || 0}}</div>
                </el-table-column>
                <el-table-column prop="productIntro" label="简介" width="280"></el-table-column>
                <el-table-column prop="addDate" label="添加日期" inline-template>
                    <div>{{new Date(row.addDate).Format('yyyy-MM-dd')}}</div>
                </el-table-column>
                <el-table-column :context="_self" fixed="right" width="200" inline-template label="操作">
                    <div>
                        <el-button size="small" @click="handleEdit($index, row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete($index, row)">删除</el-button>
                        <el-button size="small" @click="shwoDialogQrcode($index, row)">二维码</el-button>
                    </div>
                </el-table-column>
            </el-table>
            <div class="pagination-wrapper" v-show="!loading">
                <el-pagination layout="prev,pager,next,jumper,total" @current-change="handleCurrentChange" :current-page="filters.page" :total="total" :page-size="20">
                </el-pagination>
            </div>
        </div>
        <el-dialog title="保存" v-model="createDialog" size="large">
            <el-form ref="createFrom" :model="form" label-width="100px">
                <el-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item label="产品名称:" prop="product.productName">
                            <el-input placeholder="请输入商品名称" v-model="form.product.productName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="产品类型:" prop="product.productType">
                            <el-select placeholder="请选择产品类型" v-model="form.product.productType">
                                <el-option v-for="item in productTypeList" :value="item.value" :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="店铺归属:" prop="shopProduct">
                            <el-select placeholder="请选择店铺" v-model="form.shopProduct" multiple>
                                <el-option v-for="item in shopList" :value="item.id" :label="item.shopName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="价格:" prop="product.productPrice">
                            <el-input placeholder="请输入价格" v-model="form.product.productPrice"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="排序:" prop="product.productSort">
                            <el-input placeholder="请输入排序" v-model="form.product.productSort"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="产品简介:" prop="product.productIntro">
                            <el-input placeholder="请输入产品简介" type="textarea" v-model="form.product.productIntro"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="产品描述:" prop="product.productDescribe">
                            <el-input placeholder="请输入产品描述" type="textarea" v-model="form.product.productDescribe"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="首页展示图片:" prop="product.portalImg">
                            <el-upload action="v1/upload/portalImg" :on-preview="handlePortalImgPreview" :on-remove="handlePortalImgRemove" :on-success="handlePortalImgSuccess" :on-error="handlePortalImgError" :before-upload="handleBeforeUpload" :file-list="imgPortalList" list-type="picture-card">
                                <i class="el-icon-plus"></i>
                                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5mb</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="推荐展示图片:" prop="product.mainImg">
                            <el-upload action="v1/upload/mainImg" :on-preview="handleMainImgPreview" :on-remove="handleMainImgRemove" :on-success="handleMainImgSuccess" :on-error="handleMainImgError" :before-upload="handleBeforeUpload" :file-list="imgMainList" list-type="picture-card">
                                <i class="el-icon-plus"></i>
                                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5mb</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="产品详情图片:" prop="product.productImg">
                            <el-upload action="v1/upload/productImg" :on-preview="handleProductImgPreview" :on-remove="handleProductImgRemove" :on-success="handleProductImgSuccess" :on-error="handleProductImgError" :before-upload="handleBeforeUpload" :file-list="imgProductList"
                                list-type="picture-card">
                                <i class="el-icon-plus"></i>
                                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5mb</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <table class="table" style="margin-bottom:20px">
                            <thead>
                                <tr>
                                    <th>规格名字</th>
                                    <th>规格类型名</th>
                                    <th>规格类型价格</th>
                                    <th>规格类型操作</th>
                                    <th>规格操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template v-for="(item,index) in  form.product.productSpec">
                                            <tr v-for="(child,child_index) in item.productSpecItem">
                                                <td :rowspan="item.productSpecItem.length" v-if="child_index == 0">
                                                    <el-form-item label-width="0px" :prop="item.specName">
                                                        <el-input placeholder="请输入规格名字" v-model="form.product.productSpec[index].specName"></el-input>
                                                    </el-form-item>
                                                </td>
                                                <td>
                                                    <el-form-item label-width="0px" :prop="child.itemName">
                                                        <el-input placeholder="请输入规格名字" v-model="form.product.productSpec[index].productSpecItem[child_index].itemName"></el-input>
                                                    </el-form-item>
                                                </td>
                                                <td>
                                                    <el-form-item label-width="0px" :prop="child.itemPrice">
                                                        <el-input placeholder="请输入规格价格" v-model="form.product.productSpec[index].productSpecItem[child_index].itemPrice"></el-input>
                                                    </el-form-item>
                                                </td>
                                                <td>
                                                    <el-button  v-if="child_index == 0" type="success" @click.stop="addProductSpecItem(index)">新增规格类型</el-button>
                                                    <el-button  v-else type="danger" @click.stop="delProductSpecItem(index,child_index)">删除规格类型</el-button>                                            
                                                </td>
                                                <td :rowspan="item.productSpecItem.length" v-if="child_index == 0">
                                                    <el-button v-if="index == 0" type="success" @click.stop="addProductSpec()">新增规格</el-button>
                                                    <el-button v-else type="danger" @click.stop="delProductSpec(index)">删除规格</el-button>                                            
                                                </td>
                                            </tr>
</template>
                            </tbody>
                        </table>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createDialog = false">取 消</el-button>
                <el-button type="primary" @click="handleSave()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="下载二维码" v-model="qrcodeDialogVisible" size="small" @close="resetQrcodeDialog">
            <el-row style="margin-bottom: 20px;">
                <el-col :span="3">
                    <div style="line-height: 36px; text-align: right;">渠道类型：</div>
                </el-col>
                <el-col :span="20" :offset="1">
                    <el-select 
                    clearable 
                    v-model="channelType" 
                    placeholder="请选择渠道类型（可选）" 
                    @change="handleChannelTypeChange">
                        <el-option
                            v-for="item in channelTypes"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>
            <el-row v-show="channelType">
                <el-col :span="3">
                    <div style="line-height: 36px; text-align: right;">渠道值：</div>
                </el-col>
                <el-col :span="20" :offset="1">
                    <el-input 
                    v-if="channelType !== '50948b19-67b8-42ff-b857-dbd35295b89s' 
                    && channelType !== '50948b19-67b8-42ff-b857-dbd35295b80s'" 
                    v-model="channelName" 
                    placeholder="请输入渠道值">
                    </el-input>
                    <el-select v-else clearable v-model="channelName" placeholder="请选择（可选）">
                        <el-option
                            v-for="item in channelNames"
                            :label="item.shopName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20" :offset="4">
                    <p style="color: #888; font-size: 12px; line-height: 36px;">* 产品详情页二维码请在产品管理中获取</p>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetQrcodeDialog">重置</el-button>
                <el-button type="primary" @click="downloadQrcode('qr')">下载二维码</el-button>
                <el-button type="primary" @click="downloadQrcode('wx')">下载小程序码</el-button>
            </span>
            <a href="" download="" v-show="false" ref="download"></a>
        </el-dialog>
    </div>
</template>

<script>
    import {
        getProductList,
        getProductDetail,
        addProduct,
        getShopQueryAll,
        getShopList,
        getDict,
        downloadQrcode,
        deleteProduct
    } from '../../api/api';
    
    export default {
        data() {
            return {
                filters: {
                    productName: '',
                    productType: '',
                    addDate: '',
                    page:1,
                    size:20
                },
                form: {
                    product: {
                        productType: '',
                        portalImg: '',
                        mainImg: '',
                        productSpec: [{
                            specName: '',
                            productSpecItem: [{
                                itemName: '',
                                itemPrice: ''
                            }]
                        }],
                        productImg: []
                    },
                    shopProduct: []
                },
                shopList: null,
                productTypeList: null,
                tableData: null,
                loading: false,
                createDialog: false,
                imgPortalList: [],
                imgMainList: [],
                imgProductList: [],
                total:0,
                qrcodeDialogVisible: false,
                selectedProductId: '',
                channelTypes: [],
                channelNames: [],
                channelType: null,
                channelName: null,
                selectedPath: null
            }
        },
        
        methods: {
            /**
             * 下载二维码时，选择渠道类型的句柄
             */
            handleChannelTypeChange (channelType) {
                this.channelNames = [];
                this.channelName = null;
                switch (channelType) {
                    case '50948b19-67b8-42ff-b857-dbd35295b89s':
                        getShopList({
                            shopName: '',
                            shopAddress: '',
                            shopPhone: '',
                            page:0,
                        }).then(res => {
                            if (res.sysCode === 1) {
                                this.channelNames = res.data.content
                            }
                        })
                        break;
                    case '50948b19-67b8-42ff-b857-dbd35295b80s':
                        break;
                    default:
                        break;
                }
            },
            /**
             * 下载二维码
             */
            downloadQrcode(type) {        
                const channelType = this.channelType ?
                    `key=${this.channelType}` : ''
                const channelName = channelType ? 
                    (this.channelName ? `&value=${this.channelName}` : '')
                    : ''

                if (channelType && !channelName) {
                this.$message.error('请输入渠道类型相对应的值')
                    return false
                }
        
                let params = {path: `pages/detail/detail?${channelType}${channelName}`}
                type && (params.type = type)

                downloadQrcode(params).then(res => {
                    if (res.sysCode === 1) {
                    this.$refs.download.href = `https://xhlw.neocross.cn/web/${res.data}`
                    this.$refs.download.download = ''
                    this.$refs.download.click()
                    } else {
                    this.$message.error(res.errorMsg);
                    }
                })
            },
            /**
            * 重置二维码对话框数据
            */
            resetQrcodeDialog() {
                this.channelType = null
                this.channelName = null
            },
            /**
             * 打开获取二维码对话框
             */
            shwoDialogQrcode(index, row) {
                this.qrcodeDialogVisible = true
                this.selectedProductId = row.id
            },
            handleSearch() {
                this.filters.page = 1;
                this.getGrid();
            },
            handleAdd() {
                if (this.$refs['createFrom']) {
                    this.form = {
                        product: {
                            productType: '',
                            portalImg: '',
                            mainImg: '',
                            productSpec: [{
                                specName: '',
                                productSpecItem: [{
                                    itemName: '',
                                    itemPrice: ''
                                }]
                            }],
                            productImg: []
                        },
                        shopProduct: []
                    }
                    this.imgMainList = [];
                    this.imgPortalList = [];
                    this.imgProductList = [];
                }
                this.createDialog = true;
            },
            handleEdit(index, row) {
                this.loading = true;
                getProductDetail(row.id).then(result => {
                    this.loading = false;
                    let {
                        errorMsg,
                        sysCode,
                        data
                    } = result;
                    if (sysCode !== 1) {
                        this.$message.error(errorMsg);
                    } else {
                        this.imgMainList = [];
                        this.imgPortalList = [];
                        this.imgProductList = [];
                        if (data.product.productSpec.length == 0) {
                            var productSpec =  [{
                                specName: '',
                                productSpecItem: [{
                                    itemName: '',
                                    itemPrice: ''
                                }]
                            }]
                            data.product.productSpec = productSpec
                        }
                        this.form = data;
                        console.log(data.product.productSpec);
    
                        this.form.product.productType = parseInt(data.product.productType);
                        this.imgPortalList.push({
                            url: this.form.product.portalImg
                        });
                        this.imgMainList.push({
                            url: this.form.product.mainImg
                        });
                        for (let i = 0, len = data.product.productImg.length; i < len; i++) {
                            this.imgProductList.push({
                                url: data.product.productImg[i].url
                            });
                        }
                        console.log(this.form.productSpec)
                        

                        console.log(this.form.productSpec)
                        this.createDialog = true;
                    }
                });
            },
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteProduct(row.id).then(res => {
                        if (res.sysCode === 1) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getGrid()
                        } else {
                            this.$message(res.errorMsg)
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleCurrentChange(val) {
                this.filters.page = val;
                this.getGrid();
            },
            handleSave() {
                this.loading = true;
                addProduct(this.form).then(result => {
                    this.loading = false;
                    let {
                        errorMsg,
                        sysCode,
                        data
                    } = result;
                    if (sysCode !== 1) {
                        this.$message.error(errorMsg);
                    } else {
                        const msg = this.form.product.id ? '编辑成功' : '新增成功'
                        this.$message({
                            type: 'success',
                            message: msg
                        });
                    }
                });
            },
            getGrid() {
                this.loading = true;
                var params =  JSON.parse(JSON.stringify(this.filters));
                params.page = params.page - 1;
                getProductList(params).then(result => {
                    this.loading = false;
                    let {
                        errorMsg,
                        sysCode,
                        data
                    } = result;
                    if (sysCode !== 1) {
                        this.$message.error(errorMsg);
                    } else {
                        this.tableData = data.content;
                        this.filters.page =  data.number + 1;
                        this.total = data.totalElements;
                    }
                });
            },
            getShopList() {
                getShopQueryAll().then(result => {
                    let {
                        errorMsg,
                        sysCode,
                        data
                    } = result;
                    if (sysCode !== 1) {
                        this.$message.error(errorMsg);
                    } else {
                        this.shopList = data;
                    }
                });
            },
            getProductType() {
                getDict({
                    type: 'productType'
                }).then(result => {
                    let {
                        errorMsg,
                        sysCode,
                        data
                    } = result;
                    if (sysCode !== 1) {
                        this.$message.error(errorMsg);
                    } else {
                        this.productTypeList = data;
                    }
                });
            },
            handlePortalImgRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePortalImgPreview(file) {
                console.log(file);
            },
            handlePortalImgSuccess(res, file, fileList) {
                if (res.sysCode === 1) {
                    this.form.product.portalImg = res.data[0];
                }
            },
            handlePortalImgError(err, file, fileList) {
    
            },
            handleMainImgRemove(file, fileList) {
                console.log(file, fileList);
            },
            handleMainImgPreview(file) {
                console.log(file);
            },
            handleMainImgSuccess(res, file, fileList) {
                if (res.sysCode === 1) {
                    this.form.product.mainImg = res.data[0];
                }
            },
            handleMainImgError(err, file, fileList) {
    
            },
            handleProductImgRemove(file, fileList) {
                let delIdx
                this.form.product.productImg.forEach(
                    (img, idx) => {
                        if (img.imgUrl === file.url) {
                            delIdx = idx
                        }
                    }
                )
    
                if (delIdx !== undefined || delIdx !== null) {
                    this.form.product.productImg.splice(delIdx, 1)
                }
            },
            handleProductImgPreview(file) {
                console.log(file);
            },
            handleProductImgSuccess(res, file, fileList) {
                if (res.sysCode === 1) {
                    this.form.product.productImg.push({
                        imgUrl: res.data[0],
                        url: res.data[0],
                        imgSort: (this.form.product.productImg.length + 1)
                    });
                }
            },
            handleProductImgError(err, file, fileList) {
    
            },
            handleBeforeUpload(file) {
                var reg = new RegExp(/\.jpg$|\.jpeg$|\.gif$|\.png$|\.bmp$/i)
                if (!reg.test(file.name)) {
                    this.$message.error('请上传图片格式!');
                    return false
                }
    
                if (file.size > (5 * 1024 * 1024)) {
                    this.$message.error('图片最大不能超过5M!');
                    return false;
                }
            },
            addProductSpec() {
                this.form.product.productSpec.push({
                    specName: '',
                    productSpecItem: [{
                        itemName: '',
                        itemPrice: ''
                    }]
                });
            },
            delProductSpec(index) {
                this.form.product.productSpec.splice(index, 1);
            },
            addProductSpecItem(index) {
                this.form.product.productSpec[index].productSpecItem.push({
                    itemName: '',
                    itemPrice: ''
                });
            },
            delProductSpecItem(index, child_index) {
                this.form.product.productSpec[index].productSpecItem.splice(child_index, 1)
            }
        },
        mounted() {
            this.getProductType();
            this.getShopList();
            this.getGrid();

            getDict({
                type: 'channelType'
            }).then(res => {
                if (res.sysCode === 1) {
                    this.channelTypes = res.data
                }
            })
        }
    }
</script>

<style lang="scss">
    #ProductList {
        .filters {
            margin: 0 0 20px 0;
            border: 1px #efefef solid;
            padding: 10px;
            background: #f9f9f9;
            .filter {
                display: inline-block;
                width: auto;
                padding: 10px;
                border-radius: 5px;
                .el-select {
                    display: inline-block;
                }
            }
            .el-input {
                width: 150px;
                display: inline-block;
            }
        }
        .pagination-wrapper {
            text-align: center;
            padding: 30px;
        }
        .table {
            border-collapse: collapse;
            width: 100%;
            background-color: #fff;
            color: #5e6d82;
            font-size: 12px;
            border: 1px solid #e2e7ee;
            th {
                text-align: left;
                border-top: 1px solid #e2e7ee;
                background-color: #e5e9f1;
                color: #354052;
            }
            th,
            td {
                border-bottom: 1px solid #e2e7ee;
                padding: 10px;
            }
            td {
                border: 1px solid #e2e7ee;
                border-right: none;
                color: #45615e;
                &.table-empty {
                    text-align: center;
                }
                &:last-child {
                    border-right: 1px solid #e2e7ee;
                }
            }
            .el-form-item {
                margin-bottom: 0;
            }
        }
    }
</style>